package trab4.rpc;

import sim.core.*;

import trab4.grid.*;
import trab4.grid.rpc_msgs.*;

import trab4.transactions.*;
import trab4.transactions.rpc_msgs.*;

public class ServerTransactionStub extends ServerStub implements TransactionsMessageHandler, GridOperationsMessageHandler {
	
	AbstractTransactionManager<GridOperations> tm ;
	
	public ServerTransactionStub( EndPoint endpoint, AbstractTransactionManager<GridOperations> tm ) {
		super( endpoint ) ;
		this.tm = tm ;		
	}
	
	@Override
	@SuppressWarnings("unchecked")
	protected <T> T clientStub( EndPoint client ) {
		return (T) new ClientTransactionStub( client, server ) ;
	}
	
	public void onReceive( TcpChannel ch, Msg_GridSize m) {
		int[] res = tm.getByTid( m.tid).gridSize( m.tid ) ;
		ch.tcpReply( new Msg_GridReturn( res ) ) ;		
	}
	
	public void onReceive( TcpChannel ch, Msg_ReadColor m) {
		int res = tm.getByTid( m.tid).readColor(m.tid, m.i, m.j) ;
		ch.tcpReply( new Msg_GridReturn( res ) ) ;
	}

	public void onReceive( TcpChannel ch, Msg_ReadShape m) {
		int res = tm.getByTid( m.tid).readShape(m.tid, m.i, m.j) ;
		ch.tcpReply( new Msg_GridReturn( res ) ) ;
	}

	public void onReceive( TcpChannel ch, Msg_WriteColor m) {
		tm.getByTid( m.tid).writeColor(m.tid, m.i, m.j, m.v) ;
		ch.tcpReply( new Msg_GridReturn( 0 ) ) ;
	}

	public void onReceive( TcpChannel ch, Msg_WriteShape m) {
		tm.getByTid( m.tid).writeShape(m.tid, m.i, m.j, m.v ) ;
		ch.tcpReply( new Msg_GridReturn( 0 ) ) ;
	}
	
	public void onReceive(TcpChannel ch, Msg_C_OpenTransaction m) {
		long tid = tm.c_OpenTransaction() ;
		ch.tcpReply( new Msg_TransactionReturn( tid ) ) ;		
	}
	
	public void onReceive(TcpChannel ch, Msg_D_OpenTransaction m) {
		long tid = tm.d_OpenTransaction() ;
		ch.tcpReply( new Msg_TransactionReturn( tid ) ) ;		
	}
	
	public void onReceive(TcpChannel ch, Msg_C_AbortTransaction m) {
		tm.c_AbortTransaction( m.tid ) ;
		ch.tcpReply( new Msg_TransactionReturn( 0 ) ) ;		
	}

	public void onReceive(TcpChannel ch, Msg_D_AbortTransaction m) {
		tm.d_AbortTransaction( m.tid ) ;
		ch.tcpReply( new Msg_TransactionReturn( 0 ) ) ;		
	}

	public void onReceive(TcpChannel ch, Msg_C_CloseTransaction m) {
		TransactionResult res = tm.c_CloseTransaction( m.tid ) ;
		ch.tcpReply( new Msg_TransactionReturn( res ) ) ;		
	}
	
	public void onReceive(TcpChannel ch, Msg_D_CloseTransaction m) {
		TransactionResult res = tm.d_CloseTransaction( m.tid ) ;
		ch.tcpReply( new Msg_TransactionReturn( res ) ) ;		
	}
	
	public void onReceive( EndPoint src, Message m) {
		Thread.dumpStack() ;
	}

	public void onReceive( TcpChannel chn, Message m) {
		Thread.dumpStack() ;	
	}
	
	public void onSendFailure( EndPoint dst, Message m) {
	}
	
}
